package com.crealth.handler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.Config;
import com.crealth.ConstantDefine;
import com.crealth.db.ClienteleDb;
import com.crealth.db.MyselfClienteleDb;
import com.crealth.manager.ClienteleInfoManager;
import com.crealth.memcached.UserCached;
import com.crealth.model.ClienteleInfoModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.thread.ImportClienteleDetailThread;
import com.crealth.thread.ImportGroupMobiThread;
import com.crealth.utils.PhoneNumDecode;
import com.crealth.utils.Utils;


public class ClienteleInfoHandle {
	private static Logger errorLog = Logger.getLogger("error_log");
	
	public static NetMessageData obtainClienteleInfo(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		boolean dialSelfcli = false;
		if (msgJson.containsKey("dialSelfcli")) {
			dialSelfcli = true;
		}
		List<ClienteleInfoModel> clienteleInfos = ClienteleInfoManager.getClienteleModel(user, dialSelfcli);
		if (clienteleInfos != null && clienteleInfos.size() > 100) {
			JSONArray jsonArray = new JSONArray();			
			for (int index = 0; index < clienteleInfos.size(); ++index) {
				ClienteleInfoModel info = clienteleInfos.get(index);
				jsonArray.add(info.toJSONObject());
				if (jsonArray.size() == 100 || index == clienteleInfos.size()-1) {
					NetMessageData msg = new NetMessageData();
					JSONObject resJson2 = new JSONObject();
					resJson2.put("cnt", clienteleInfos.size());
					resJson2.put("clienteles", jsonArray);
					resJson2.put("index", index+1);
					msg.setMsgBody(resJson2.toJSONString());
					ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), userID, msg);
					jsonArray = new JSONArray();
				}
			}
			return null;
		}
		
		JSONArray jsonArray = new JSONArray();
		if (clienteleInfos != null) {
			for (ClienteleInfoModel info : clienteleInfos) {
				jsonArray.add(info.toJSONObject());
			}
			resJson.put("cnt", clienteleInfos.size());
		} else {
			resJson.put("cnt", 0);
		}
		
		resJson.put("clienteles", jsonArray);		
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData addClienteleInfo(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		
		List<ClienteleInfoModel> cliModels = new ArrayList<ClienteleInfoModel>();
		int userID = msgJson.getIntValue("id");
		JSONArray jsonArray = msgJson.getJSONArray("addClientele");
		for (int idx = 0; idx < jsonArray.size(); idx++) {
            JSONObject jo = jsonArray.getJSONObject(idx);
            ClienteleInfoModel clienteleInfo = new ClienteleInfoModel();
            clienteleInfo.fromJson(jo);
            if (Config.mobiPhoneEncrypt) {
            	String strMobi = clienteleInfo.getMobi();
            	strMobi = PhoneNumDecode.encryptPhone(strMobi);
            	clienteleInfo.setMobi(strMobi);
            }
            if (clienteleInfo.getMobi().length() != 11) {
            	continue;
            }
            clienteleInfo.setCreaterUserID(userID);
            cliModels.add(clienteleInfo);
		}
		ClienteleInfoManager.addClienteleModel(cliModels);
		ClienteleInfoManager.initMaxID();
		
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData searchClienteleInfo(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		if (Config.showSearchConsumerInfo == 0) {
			return null;
		}
		String searchMobi = msgJson.getString("searchMobi");
		List<ClienteleInfoModel> searchRes1 = null;
		if (searchMobi == null || searchMobi.length() < 5) {
			return null;
		}
		if (Config.mobiPhoneEncrypt) {
			searchMobi = PhoneNumDecode.decryptPhone(searchMobi);
		}
		searchRes1  = MyselfClienteleDb.selectClienteleInfoByMobi(searchMobi, userID);
		//  公共库
		List<ClienteleInfoModel> globleRes = ClienteleDb.selectClienteleInfoByMobi(searchMobi);
		if (globleRes != null && globleRes.size() > 0) {
			for (ClienteleInfoModel info : globleRes) {
				//albbInfo.setType("ALBBSJ");
				searchRes1.add(info);
			}
		}
		//  查找 阿里巴巴数据
		List<ClienteleInfoModel> albbInfols = ClienteleDb.selectClienteleInfoFromAlbbByMobi(searchMobi);
		if (albbInfols != null && albbInfols.size() > 0) {
			for (ClienteleInfoModel albbInfo : albbInfols) {
				//albbInfo.setType("ALBBSJ");
				searchRes1.add(albbInfo);
			}
		}
		
		JSONArray jsonArray = new JSONArray();
		int cnt = 0;
		//ArrayList<String> nameArray = new ArrayList<String>();
		if (searchRes1 != null && searchRes1.size() > 0) {
			cnt = searchRes1.size();
			for (ClienteleInfoModel info : searchRes1) {
				jsonArray.add(info.toJSONObject());
				/*
				String strName = info.getName();
				if (strName != null && strName.length() > 0) {
					nameArray.add(strName);
				}*/			
			}
		}
		/*
		if (nameArray.size() > 0) {
			String searchName = StringUtil.mergeStringToSql(nameArray);
			List<ClienteleInfoModel> searchRes2 = null;
			if (searchName != null && searchName.length() > 0) {
				searchRes2 = ClienteleDb.selectClienteleInfoByName(searchName);
			}
			if (searchRes2 != null && searchRes2.size() > 0) {
				cnt += searchRes2.size();
				for (ClienteleInfoModel info : searchRes2) {
					jsonArray.add(info.toJSONObject());
				}
			}
		}*/
		
		resJson.put("cnt", cnt);
		resJson.put("clienteles", jsonArray);		
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData deleteSelfClient(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() != ConstantDefine.Sales_Man && 
			user.getPosition() != ConstantDefine.Group_Leader && 
			user.getPosition() != ConstantDefine.Team_Manager) {
			return null;
		}
		
		MyselfClienteleDb.deleteClienteleByCreateID(userID);
		resJson.put("resCode", 0);
		//resJson.put("delNum", res);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData deleteAllClient(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Branch_Mgr_Fu ) {
			return null;
		}
		
		ClienteleDb.deleteAllClient();
		resJson.put("resCode", 0);
		//resJson.put("delNum", res);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData obtainCallPhoneNum(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() >= ConstantDefine.Head_Manager) {
			Integer allSum = ClienteleDb.selectGroupCallMobiSumNum();
			Integer nocallNum = ClienteleDb.selectGroupCallMobiNotCallNum();
			Integer alreadyCallNum = ClienteleDb.selectGroupCallMobiAlreadyCallNum();
			Integer holdNum = ClienteleDb.selectGroupCallMobiHold();
			Integer notDispenseNum = ClienteleDb.selectGroupCallMobiNotDispense();
			resJson.put("allPhoneNum", allSum);
			resJson.put("noCallNum", nocallNum);
			resJson.put("holdNum", holdNum);
			resJson.put("notDispenseNum", notDispenseNum);
			resJson.put("alreadyCallNum", alreadyCallNum);
		} else if (user.getPosition() == ConstantDefine.Branch_Mgr_Fu || 
			user.getPosition() == ConstantDefine.Branch_Mgr   ) {
			int companyID = user.getBelongCompanyID();
			Integer allSum = ClienteleDb.selectGroupCallMobiSumNum2(companyID);
			Integer nocallNum = ClienteleDb.selectGroupCallMobiNotCallNum2(companyID);
			Integer alreadyCallNum = ClienteleDb.selectGroupCallMobiAlreadyCallNum2(companyID);
			Integer holdNum = ClienteleDb.selectGroupCallMobiHold2(companyID);
			Integer notDispenseNum = ClienteleDb.selectGroupCallMobiNotDispense2(companyID);
			resJson.put("allPhoneNum", allSum);
			resJson.put("noCallNum", nocallNum);
			resJson.put("holdNum", holdNum);
			resJson.put("notDispenseNum", notDispenseNum);
			resJson.put("alreadyCallNum", alreadyCallNum);
		} else {
			Integer allSum = MyselfClienteleDb.selectUserClienteleSumNum(userID);
			Integer nocallNum = MyselfClienteleDb.selectUserClienteleNotCallNum(userID);
			resJson.put("allPhoneNum", allSum);
			resJson.put("noCallNum", nocallNum);
		}		
		
		resJson.put("resCode", 0);		
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	//  上传  群呼的号码
	public static NetMessageData uploadGroupCallMobi(NetMessageData revData) {		
		//NetMessageData sendMsg = new NetMessageData();
		//JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			errorLog.error("uploadGroupCallMobi msgJson is null");
			return null;
		}
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		/*
		if (user.getPosition() < ConstantDefine.Branch_Company_Mgr) {
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		*/
		String dtype = msgJson.getString("dtype");
		String data = msgJson.getString("data");
		String fileName = msgJson.getString("fileName");
		String fileDir = "./uploadData/";
		String osName = Utils.getOSName();
		Utils.checkAndCreateDir(fileDir);
		if (osName.startsWith("Window")) {
		}
		else {
			File f = new File(fileDir);
	        f.setWritable(true, false);			
		}
		Utils.saveUploadFile(userID, dtype, data, 
				fileName, fileName, fileDir);
		
		int needDel = 0;
		if (msgJson.containsKey("param2")) {
			needDel = msgJson.getIntValue("param2");
		}
		boolean bDelPreData = false;
		if (needDel == 1) {
			bDelPreData = true;
		}
		ImportGroupMobiThread importThread = new ImportGroupMobiThread(fileName, bDelPreData, user);
		if (user.getPosition() >= ConstantDefine.Head_Manager) {
			int comID = user.getBelongCompanyID();
			if (msgJson.containsKey("toCompanyID")) {
				comID = msgJson.getIntValue("toCompanyID");
			}
			importThread.setCompanyID(comID);
		}
		importThread.start();
		
		return null;
	}
	
	//  客户资料  详细信息
	public static NetMessageData uploadClienteleDetail(NetMessageData revData) {		
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			errorLog.error("uploadClienteleDetail msgJson is null");
			return null;
		}
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		
		String dtype = msgJson.getString("dtype");
		String data = msgJson.getString("data");
		String fileName = msgJson.getString("fileName");
		String fileDir = "./uploadData/";
		String osName = Utils.getOSName();
		Utils.checkAndCreateDir(fileDir);
		if (osName.startsWith("Window")) {
		}
		else {
			File f = new File(fileDir);
	        f.setWritable(true, false);					
		}
		Utils.saveUploadFile(userID, dtype, data, 
				fileName, fileName, fileDir);
		
		boolean bDelPreData = false;
		if (msgJson.containsKey("param2")) {
			int needDel = msgJson.getIntValue("param2");
			if (needDel == 1) {
				bDelPreData = true;
			}
		}		
		
		if (bDelPreData && user.getPosition() >= ConstantDefine.Branch_Mgr) {
			ClienteleDb.deleteAllClient();
		}
		
		ImportClienteleDetailThread importThread = new ImportClienteleDetailThread(fileName, user);
		if (msgJson.containsKey("fieldMap")) {
			JSONObject fieldMapJson = msgJson.getJSONObject("fieldMap");
			importThread.setFieldMapJson(fieldMapJson);
		}
		
		importThread.start();
		
		return null;
	}
	
	private static String combinationSqlCondition(String strSqlResult, String strSql) {
		if (strSqlResult.length() > 0) {
			strSqlResult += " AND " + strSql;
		} else {
			strSqlResult = strSql;
		}
		
		return strSqlResult;
	}
	
	public static NetMessageData conditionSearchClienteleInfo(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		
		String strSqlCondition = "";
		String strValue;
		String strSql;
		if (msgJson.containsKey("name")) {
			strValue = msgJson.getString("name");
			strSql = String.format("`Name` like '%%%s%%' ", strValue);
			strSqlCondition = strSql;
		}
		if (msgJson.containsKey("phoneNum")) {
			strValue = msgJson.getString("phoneNum");
			strSql = String.format("`Mobi` like '%%%s%%' ", strValue);
			strSqlCondition = combinationSqlCondition(strSqlCondition, strSql);
		}
		if (msgJson.containsKey("homeAddr")) {
			strValue = msgJson.getString("homeAddr");
			strSql = String.format("`Hous` like '%%%s%%' ", strValue);
			strSqlCondition = combinationSqlCondition(strSqlCondition, strSql);
		}
		if (msgJson.containsKey("companyAddr")) {
			strValue = msgJson.getString("companyAddr");
			strSql = String.format("`Addr` like '%%%s%%' ", strValue);
			strSqlCondition = combinationSqlCondition(strSqlCondition, strSql);
		}
		if (msgJson.containsKey("companyName")) {
			strValue = msgJson.getString("companyName");
			strSql = String.format("`Unit` like '%%%s%%' ", strValue);
			strSqlCondition = combinationSqlCondition(strSqlCondition, strSql);
		}
		if (msgJson.containsKey("type")) {
			strValue = msgJson.getString("type");
			strSql = String.format("`Type` = '%s' ", strValue);
			strSqlCondition = combinationSqlCondition(strSqlCondition, strSql);
		}
		if (msgJson.containsKey("searchID")) {
			strValue = msgJson.getString("searchID");
			strSql = String.format("%s > `Id`", strValue);
			strSqlCondition = combinationSqlCondition(strSqlCondition, strSql);
		}
		if (msgJson.containsKey("memo")) {
			strValue = msgJson.getString("memo");
			strSql = String.format("`Dscr` like '%%%s%%' ", strValue);
			strSqlCondition = combinationSqlCondition(strSqlCondition, strSql);
		}
		
		Integer searchNum = ClienteleDb.selectClienteleCntByCondition(strSqlCondition);
		if (searchNum == null) {
			return null;
		}
		if (searchNum > 2000 || searchNum == 0) {
			resJson.put("searchResultNum", searchNum);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		List<ClienteleInfoModel> clienteleInfos = ClienteleDb.selectClienteleInfoByCondition(strSqlCondition);
		if (clienteleInfos != null && clienteleInfos.size() > 100) {
			JSONArray jsonArray = new JSONArray();			
			for (int index = 0; index < clienteleInfos.size(); ++index) {
				ClienteleInfoModel info = clienteleInfos.get(index);
				jsonArray.add(info.toJSONObjectOnlyMobi());
				if (jsonArray.size() == 100 || index == clienteleInfos.size()-1) {
					NetMessageData msg = new NetMessageData();
					JSONObject resJson2 = new JSONObject();
					resJson2.put("cnt", clienteleInfos.size());
					resJson2.put("clienteles", jsonArray);
					resJson2.put("index", index+1);
					resJson2.put("searchResultNum", searchNum);
					msg.setMsgBody(resJson2.toJSONString());
					ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), userID, msg);
					jsonArray = new JSONArray();
				}
			}
			return null;
		}
		
		JSONArray jsonArray = new JSONArray();
		if (clienteleInfos != null) {
			for (ClienteleInfoModel info : clienteleInfos) {
				jsonArray.add(info.toJSONObjectOnlyMobi());
			}
		}
		resJson.put("searchResultNum", searchNum);
		resJson.put("cnt", clienteleInfos.size());
		resJson.put("clienteles", jsonArray);		
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	
}
